package com.reactnativestudy.model;

import androidx.annotation.NonNull;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ReactBundle {
    private String name;
    private String bundle;
    private String hash;
    private String entry;
    private List<ReactBundle> dependencies;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBundle() {
        return bundle;
    }

    public void setBundle(String bundle) {
        this.bundle = bundle;
    }

    public List<ReactBundle> getDependencies() {
        return dependencies;
    }

    public void setDependencies(List<ReactBundle> dependencies) {
        this.dependencies = dependencies;
    }

    public String getHash() {
        return hash;
    }

    public void setHash(String hash) {
        this.hash = hash;
    }

    public String getEntry() {
        return entry;
    }

    public void setEntry(String entry) {
        this.entry = entry;
    }

    public static ReactBundle toObject(String jsonString) throws JSONException {
        if(jsonString == null || jsonString.isEmpty()){
            return null;
        }
        ReactBundle reactBundle = new ReactBundle();

        JSONObject jsonObject = new JSONObject(jsonString);
        reactBundle.setName(jsonObject.optString("name"));
        reactBundle.setHash(jsonObject.optString("hash"));
        reactBundle.setEntry(jsonObject.optString("entry"));
        reactBundle.setBundle(jsonObject.optString("bundle"));
        JSONArray array = jsonObject.optJSONArray("dependencies");
        if (array != null){
            List<ReactBundle> dependencies = new ArrayList<>();
            for (int i = 0; i < array.length(); i++) {
                JSONObject object = array.getJSONObject(i);
                dependencies.add(toObject(object.toString()));
            }
            reactBundle.setDependencies(dependencies);
        }
        return reactBundle;
    }
    private JSONObject toJson(){
        JSONObject object = new JSONObject();
        try {
            object.put("name", this.name);
            object.put("hash", this.hash);
            object.put("entry", this.entry);
            object.put("bundle", this.bundle);

            if(this.dependencies != null){
                JSONArray array = new JSONArray();
                for (ReactBundle bundle :
                        this.dependencies) {
                    array.put(bundle.toJson());
                }
                object.put("dependencies", array);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return object;
    }

    @NonNull
    @Override
    public String toString() {
        return toJson().toString();
    }
}
